<script lang="ts" setup>
import { ref } from 'vue'

enum FormItemTypeEnums {
  textInput = 'text-input',
  paragraph = 'paragraph',
  select = 'select',
}

export type IFormItem = {
  type: FormItemTypeEnums
  label: string
  variable: string
  required: boolean
  default: string
  options?: string[]
}

const props = defineProps<{
  formItems: IFormItem[]
}>()

const defaultForm: { [key: string]: string } = {}
if (props.formItems) {
  for (const formItem of props.formItems) {
    defaultForm[formItem.variable] = formItem.default
  }
}

const rules = {
  isRequired: (formItem: IFormItem) => {
    return (value: string) => {
      if (formItem.required && !value) {
        return `${formItem.label}不能为空`
      }
      return true
    }
  },
}

const form = ref()
const formData = ref<{ [key: string]: string }>(defaultForm)

const validate = async () => {
  const { valid } = await form.value.validate()
  return valid
}

defineExpose({
  validate,
  formData,
})
</script>

<template>
  <div class="user-input-form">
    <v-form ref="form" v-if="props.formItems">
      <template v-for="(formItem, index) in props.formItems">
        <template v-if="FormItemTypeEnums.textInput === formItem.type">
          <v-text-field
            :key="index"
            v-model="formData[formItem.variable]"
            :label="formItem.label"
            :rules="[rules.isRequired(formItem)]"
            variant="outlined"
            clearable
            hide-details
            density="compact"
          ></v-text-field>
        </template>
        <template v-else-if="FormItemTypeEnums.paragraph === formItem.type">
          <v-textarea
            :key="index"
            v-model="formData[formItem.variable]"
            :label="formItem.label"
            :rules="[rules.isRequired(formItem)]"
            variant="outlined"
            clearable
            hide-details
            density="compact"
          ></v-textarea>
        </template>
        <template v-else-if="FormItemTypeEnums.select === formItem.type">
          <v-select
            :key="index"
            v-model="formData[formItem.variable]"
            :label="formItem.label"
            :rules="[rules.isRequired(formItem)]"
            :items="formItem.options"
            variant="outlined"
            clearable
            hide-details
            density="compact"
          ></v-select>
        </template>
      </template>
    </v-form>
  </div>
</template>
